package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoLoginFilter",value = "")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //俩对象转型
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;

        //判断session当中是否右用户
        User user = (User) request.getSession().getAttribute("user");
        //判断用户是否为空
        if (user==null&&user.equals("")){
            chain.doFilter(req, resp);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie:cookies){
                if (cookie.equals("userinfo")){
                    String decode = Base64Utils.decode(cookie.getValue());
                    String[] split = decode.split("#");
                    String username = user.getUsername();
                    String password = user.getPassword();

                    if (username.equals(split[0])&&password.equals(split[1])){
                        UserService userService=new UserServiceImpl();
                        User login = userService.login(username, password);
                        request.getSession().setAttribute("user",login);

                    }else {
                        Cookie cookie1=new Cookie("userinfo","");
                        cookie1.setHttpOnly(true);
                        cookie1.setMaxAge(0);
                        cookie1.setPath(request.getContextPath());
                        response.addCookie(cookie1);
                    }
                }

            }

        }
        //获取页面所有的cookie
        //判断cookie不为空
        //循环显示cookie
        //判断账户名是否右userinfo这个cookie
        //解密
        //拆分为字符串#
        //调用业务  login
        //判断业务返回的对象是否为空
        //不为空则再次加载入session会话名
        //为空那么清除此cookie 创建，上下文，时间0 http

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
